<template>
  <div class="ai-chat-settings-panel">
    <AxiomTitle title="AI 对话设置" type="component" description="配置知识库及语言模型" />
    <AxiomForm ref="formRef" :model="formState" label-position="top" class="mt-4">
      <AxiomFormItem label="知识库" prop="kb_ids">
        <AxiomSelect
          v-model="formState.kb_ids"
          placeholder="请选择要查询的知识库"
          :options="knowledgeBaseOptions"
          multiple
          filterable
          collapse-tags
          collapse-tags-tooltip
          block
        />
      </AxiomFormItem>

      <AxiomFormItem label="知识库查询预设" prop="query_preset">
        <AxiomSelect
          v-model="selectedPresetId"
          placeholder="加载知识库预设"
          :options="queryPresetOptions"
          :disabled="!formState.kb_ids.length"
          clearable
          block
          @change="applyKnowledgePreset"
        >
          <template #option="{ option }">
            <AxiomGroup justify="space-between" align="center" class="w-full">
              <span>{{ option.label }}</span>
              <AxiomIcon v-if="option.is_default" name="StarFilled" style="color: var(--axiom-color-warning);" />
            </AxiomGroup>
          </template>
        </AxiomSelect>
      </AxiomFormItem>

       <AxiomFormItem label="语言模型" prop="llm_profile_name">
        <AxiomSelect
          v-model="formState.llm_profile_name"
          placeholder="请选择一个语言模型"
          :options="llmProfileOptions"
          block
        />
      </AxiomFormItem>

    </AxiomForm>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, inject } from 'vue';
import {
  AxiomForm, AxiomFormItem, AxiomSelect, AxiomTitle, AxiomIcon, AxiomGroup,
} from 'axiom-view';
import { knowledgeBaseApi } from '@/api/knowledge/knowledgeBase';
import { presetApi } from '@/api/knowledge/preset';
import { chatApi } from '@/api/ai/chat'; // New API module

// --- Data State ---
const formRef = ref(null);
const formState = reactive({
  kb_ids: [],
  llm_profile_name: null,
  search_config: null, // To store the selected preset config
});

const knowledgeBases = ref([]);
const queryPresets = ref([]);
const llmProfiles = ref([]);

const selectedPresetId = ref(null);

const { notification } = inject('axiom-utils');

// --- Computed Options for Selects ---
const knowledgeBaseOptions = computed(() => 
  knowledgeBases.value.map(kb => ({ label: kb.name, value: kb.id }))
);

const queryPresetOptions = computed(() => 
  queryPresets.value.map(p => ({ label: p.name, value: p.id, is_default: p.is_default }))
);

const llmProfileOptions = computed(() => 
  llmProfiles.value.map(p => ({ label: `${p.provider}: ${p.model_name}`, value: p.profile_name }))
);

// --- API Calls ---
async function fetchInitialData() {
  try {
    const [kbRes, llmRes] = await Promise.all([
      knowledgeBaseApi.listAllSimple(),
      chatApi.listLlmProfiles(),
    ]);
    if (kbRes.success) knowledgeBases.value = kbRes.data;
    if (llmRes.success) {
      llmProfiles.value = llmRes.data;
      // Set default LLM if available
      if (llmProfiles.value.length > 0) {
        formState.llm_profile_name = llmProfiles.value[0].profile_name;
      }
    }
  } catch (error) {
    console.error("Failed to fetch initial data for settings panel:", error);
  }
}

async function fetchPresetsForKb() {
  formState.search_config = null; // Reset config when KBs change
  selectedPresetId.value = null;

  if (formState.kb_ids.length === 0) {
    queryPresets.value = [];
    return;
  }
  try {
    const res = await presetApi.getByKbIds(formState.kb_ids);
    if (res && res.success) {
      queryPresets.value = res.data || [];
      const defaultPreset = queryPresets.value.find(p => p.is_default);
      if (defaultPreset) {
        selectedPresetId.value = defaultPreset.id;
        applyKnowledgePreset(defaultPreset.id);
      }
    }
  } catch (error) {
    console.error("Failed to fetch presets for knowledge bases:", error);
  }
}

// --- Logic ---
function applyKnowledgePreset(presetId) {
  if (!presetId) {
    formState.search_config = null;
    return;
  }
  
  const preset = queryPresets.value.find(p => p.id === presetId);
  if (preset && preset.config) {
    formState.search_config = preset.config;
    notification.success({ title: '成功', message: `已应用知识库预设: ${preset.name}`});
  }
}

// --- Watchers ---
watch(() => formState.kb_ids, fetchPresetsForKb, { deep: true });

// --- Lifecycle ---
onMounted(fetchInitialData);

// --- Expose to Parent ---
defineExpose({
  getSettings: () => {
    return JSON.parse(JSON.stringify(formState));
  }
});
</script> 